package com.bright.ghj.user.util;

import com.bright.ghj.common.util.StringUtil;
import com.bright.ghj.user.pojo.dto.CommonUserDTO;
import com.bright.ghj.user.security.SecurityUser;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

/**
 * @Author txf, hxj
 * @Date 2022/7/27 15:47
 * @Description
 */
public class SecurityUtil {

    public static <T extends CommonUserDTO> T getLoginUser() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        SecurityUser<T> securityUser = null;
        if ("anonymousUser".equals(principal.toString())) {
            //临时
            securityUser = new SecurityUser<T>();
        } else {
            securityUser = (SecurityUser<T>) principal;
        }

        T user;
//        if (securityUser.getUser() == null) {
//            // 临时
//            user = new UserDTO(null, "超级用户");
//        } else {
        user = securityUser.getUser();
//        }

        return user;

    }

    public static String getDomainOfRequestUrl(HttpServletRequest request) throws MalformedURLException {
        String requestURL = request.getHeader("referer");
        if (StringUtil.isEmpty(requestURL)) {
            requestURL = request.getRequestURL().toString();
        }
        // System.err.println("获取的域名地址:"+requestURL);
        URL parsedUrl = new URL(requestURL);
        // System.err.println("解析的域名地址:"+domain);
        return parsedUrl.getHost();
    }

    public static String getMatchedDomainUrl(List<String> urls, String domain) {
        if (urls == null) return null;
        if (urls.size() == 1) return urls.get(0);

        String result = null;
        for (String s : urls) {
            if (s.contains(domain)) {
                result = s;
            }
        }
        return result;
    }


}
